package logic

import (
	"bytes"
	"encoding/json"
	"fmt"
	"imagesearch/internal/config"
	"io"
	"net/http"
	"os"
)

type PicStoreResponse struct {
	Ret     bool    `json:"ret""`
	PicInfo PicInfo `json:"info"`
}

type PicInfo struct {
	Md5  string `json:"md5""`
	Size int    `json:"size""`
}

func PreserveImage(conf config.ImageConfig, filePath string) (string, error) {
	byte, err := os.ReadFile(filePath)
	var reqUrl = conf.Url + conf.Method
	res, err := http.Post(reqUrl, "jpeg", bytes.NewReader(byte))
	if err != nil {
		fmt.Println("err=", err)
		return "", nil
	}
	defer func() {
		res.Body.Close()
		fmt.Println("finish")
	}()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(" post err=", err)
	}
	var resp PicStoreResponse
	json.Unmarshal(body, &resp)
	var picUrl = conf.Url + resp.PicInfo.Md5
	fmt.Println(" url:", picUrl)
	return picUrl, nil
}
